/**
 * BaiduWeather.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2014年10月19日
 */
package com.pshare.weather.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.pshare.framework.annotation.Cacheablex;
import com.pshare.framework.exception.SeaxRuntimeException;

/**
 * 百度天气预报接口
 */
public class BaiduWeather {
	private static Map<String, String> weatherPic = new HashMap<String, String>();
	
	
	static{
		String weathers = "晴:多云:阴:阵雨:雷阵雨:雷阵雨伴有冰雹:雨夹雪:小雨:中雨:大雨:暴雨:大暴雨:特大暴雨:阵雪:小雪:中雪:大雪:暴雪:雾:冻雨:沙尘暴:小雨转中雨:中雨转大雨:大雨转暴雨:暴雨转大暴雨:大暴雨转特大暴雨:小雪转中雪:中雪转大雪:大雪转暴雪:浮尘:扬沙:强沙尘暴:霾";
		String[] weather = weathers.split(":");
		for (int i =0;i<weather.length;i++) {
			weatherPic.put(weather[i], i+"");
		}
	}
	
	// 获取天气信息
	public static JSONObject GetWeater(String city) {
		JSONObject buffstr = null;
		if(city==null){
			throw new SeaxRuntimeException();
		}
		try {
			String xml = getXmlCode(URLEncoder.encode(city, "utf-8")); // 设置输入城市的编码，以满足百度天气api需要
			buffstr = readStringXml(xml);// 调用xml解析函数
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffstr;
	}

	public static String getXmlCode(String city) throws UnsupportedEncodingException {
		String requestUrl = "http://api.map.baidu.com/telematics/v3/weather?location=" + city
				+ "&output=xml&ak=A72e372de05e63c8740b2622d0ed8ab1";
		StringBuffer buffer = null;
		try {
			// 建立连接
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoInput(true);
			httpUrlConn.setRequestMethod("GET");
			// 获取输入流
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			// 读取返回结果
			buffer = new StringBuffer();
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}

			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			httpUrlConn.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString(); // 返回获取的xml字符串
	}

	public static JSONObject readStringXml(String xml) {
		StringBuffer buff = new StringBuffer(); // 用来拼接天气信息的
		Document doc = null;
		List listdate = null; // 用来存放日期
		List listday = null; // 用来存放白天图片路径信息
		List listweather = null;
		List listwind = null;
		List listtem = null;
		try {
			// 读取并解析XML文档
			// 下面的是通过解析xml字符串的
			doc = DocumentHelper.parseText(xml); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点
			Iterator iter = rootElt.elementIterator("results"); // 获取根节点下的子节点results
			String status = rootElt.elementText("status"); // 获取状态，如果等于success,表示有数据
			if (!status.equals("success"))
				return new JSONObject(); // 如果不存在数据，直接返回
			String date = rootElt.elementText("date"); // 获取根节点下的，当天日期
			buff.append(date + "\n");
			// 遍历results节点
			while (iter.hasNext()) {
				Element recordEle = (Element) iter.next();
				Iterator iters = recordEle.elementIterator("weather_data"); //
				// 遍历results节点下的weather_data节点
				while (iters.hasNext()) {
					Element itemEle = (Element) iters.next();
					listdate = itemEle.elements("date");
					// 将date集合放到listdate中
					listday = itemEle.elements("dayPictureUrl");
					listweather = itemEle.elements("weather");
					listwind = itemEle.elements("wind");
					listtem = itemEle.elements("temperature");
				}
				for (int i = 0; i < listdate.size(); i++) { // 由于每一个list.size都相等，这里统一处理
					Element eledate = (Element) listdate.get(i); // 依次取出date
					Element eleday = (Element) listday.get(i);// ..
					Element eleweather = (Element) listweather.get(i);
					Element elewind = (Element) listwind.get(i);
					Element eletem = (Element) listtem.get(i);
					int weather12 = eledate.getText().indexOf("实时：");
					JSONObject currentWeather = new JSONObject();
					currentWeather.put("weather", eledate.getTextTrim().substring(weather12+3, eledate.getTextTrim().length()-1));
					
					String code = weatherPic.get(eleweather.getText());
					if(code==null){
						code=weatherPic.get(eleweather.getText().split("转")[0]);
					}
					 
					currentWeather.put("pic", code);
					 
					buff.append(eledate.getText() + "===" + eleweather.getText() + "===" + elewind.getText() + "==="
							+ eletem.getText() + "\n"); // 拼接信息
					System.out.println(buff);
					return currentWeather ;
					// *****************如果想用到微信公众号上，还请自己继续写代码，我只能帮到这了，数据已经分离开了。
					// 微信天气处理 省略
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONObject();
	}


}
